# -*- coding: utf-8 -*-
from App.app.admin.crud.sys_config_crud import SysConfigDao
from App.app.admin.schemas.sys_config_schema import UpdateSysConfigParam, SysConfigSchema, CreateSysConfigParam
from App.common.exception.errors import CustomError
from App.database.mysql import async_db_session
from App.utils.serializers import select_as_dict


class SysConfigServices:
    @staticmethod
    async def get() -> SysConfigSchema:
        async with async_db_session() as db:
            sys_config = await SysConfigDao.get(db)
            return SysConfigSchema.model_validate(sys_config) if sys_config else SysConfigSchema()

    @staticmethod
    async def update(*, obj_in: UpdateSysConfigParam):
        async with async_db_session.begin() as db:
            pk = obj_in.id
            if pk:
                config = await SysConfigDao.get(db)
                if not config:
                    raise CustomError(message="ID有误，请核实后在试")
                if config.id != int(pk):
                    raise CustomError(message="ID有误，请核实后在试")
                await SysConfigDao.update(db, pk=int(pk), obj_in=obj_in)
            else:
                create_data = select_as_dict(obj_in)
                create_data.pop('id')
                obj = CreateSysConfigParam(**create_data)
                await SysConfigDao.create(db, obj)


SysConfigService: SysConfigServices = SysConfigServices()
